<script setup>
	import { computed, ref, watch } from 'vue'
	import { useSimpleQueryStore } from '@/views/plugin/dashboard/store/simpleQuery'

	// 转换为小写驼峰格式的函数
	const toCamelCase = (str) => {
		// 如果字符串中包含括号，分离括号内外的内容
		const matches = str.match(/(.*?)\s*\((.*?)\)\s*$/)
		if (matches) {
			// 处理括号外的部分为驼峰格式
			const mainPart = matches[1].toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase())
			// 保持括号内的内容不变
			return `${mainPart} (${matches[2]})`
		}
		// 如果没有括号，按原来的方式处理
		return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase())
	}

	const store = useSimpleQueryStore()

	const props = defineProps({
		modelValue: {
			type: Boolean,
			default: false
		},
		tableName: {
			type: String,
			default: ''
		},
		conditions: {
			type: Array,
			default: () => []
		}
	})

	const emit = defineEmits(['update:modelValue'])
	const visible = ref(props.modelValue)

	// 监听modelValue变化
	watch(
		() => props.modelValue,
		(newVal) => {
			visible.value = newVal
		}
	)

	// 监听visible变化
	watch(visible, (newVal) => {
		emit('update:modelValue', newVal)
	})

	// 切换弹窗显示状态
	const togglePreview = () => {
		visible.value = !visible.value
	}

	// 暴露togglePreview方法供外部调用
	defineExpose({
		togglePreview
	})

	// 获取操作符的中文描述
	const getOperatorLabel = (operator) => {
		const operatorMap = {
			eq: '等于',
			neq: '不等于',
			gt: '大于',
			lt: '小于',
			gte: '大于等于',
			lte: '小于等于',
			like: '包含',
			not_like: '不包含',
			in: '在列表中',
			not_in: '不在列表中',
			between: '在范围内',
			not_between: '不在范围内',
			is_null: '为空',
			is_not_null: '不为空',
			is_empty: '为空字符串',
			is_not_empty: '不为空字符串'
		}
		return operatorMap[operator] || operator
	}

	// 获取格式化类型的中文描述
	const getFormatTypeLabel = (typeParam) => {
		const formatTypes = [
			{ value: 'datetime', label: '时间格式化', formats: ['YYYY-MM-DD', 'YYYY-MM-DD HH:mm:ss', 'HH:mm:ss'] },
			{ value: 'mask', label: '数据脱敏', formats: ['手机号', '身份证号', '银行卡号', '自定义'] },
			{ value: 'fieldname', label: '修改名称', formats: ['自定义'] }
		]
		const formatType = formatTypes.find((type) => type.value === typeParam)
		if (formatType) {
			return formatType.label
		}
		return ''
	}

	// 获取选中的列名称
	const selectedColumnNames = computed(() => {
		return store.formData.itemConfig.columns
			.filter((col) => store.formData.itemConfig.selectedColumns.includes(col.key))
			.map((col) => (store.formData.itemConfig.enableCamelCase ? toCamelCase(col.title) : col.title))
			.join('、')
	})

	// 获取条件描述
	const getConditionDescription = (condition) => {
		const fieldTitle =
			store.formData.itemConfig.columns.find((col) => col.key === condition.field)?.title || condition.field
		const fieldLabel = store.formData.itemConfig.enableCamelCase ? toCamelCase(fieldTitle) : fieldTitle
		const operatorLabel = getOperatorLabel(condition.operator)

		if (['is_null', 'is_not_null', 'is_empty', 'is_not_empty'].includes(condition.operator)) {
			return `${fieldLabel} ${operatorLabel}`
		}

		if (['between', 'not_between'].includes(condition.operator)) {
			const [start, end] = condition.value || []
			return `${fieldLabel} ${operatorLabel} ${start || ''} 至 ${end || ''}`
		}

		return `${fieldLabel} ${operatorLabel} ${condition.value || ''}`
	}

	// 获取格式化配置描述
	const getFormatDescription = (format) => {
		return store.formData.itemConfig.columns.find((col) => col.key === format.field)?.title || format.field
	}
	// 获取字段名称
	const getFieldName = (fieldKey) => {
		const field = store.formData.itemConfig?.columns.find((col) => col.key === fieldKey)
		return field ? field.title : fieldKey
	}
	// 获取排序方式的中文描述
	const getSortOrderText = (order) => {
		const orderMap = {
			asc: '正序',
			desc: '倒序'
		}
		return orderMap[order] || order
	}
</script>

<template>
	<a-tooltip title="配置预览">
		<a-popover v-model:open="visible" trigger="click" placement="rightTop" overlay-class-name="config-preview-popover">
			<template #content>
				<div class="config-preview-panel">
					<div class="panel-header flex justify-between items-center mb-4">
						<span>配置预览</span>
					</div>
					<a-descriptions bordered :column="1" size="small" :label-style="{ width: '110px', 'text-align': 'left' }">
						<a-descriptions-item label="数据表">
							{{ store.formData.itemConfig.tableName || '未选择' }}
						</a-descriptions-item>
						<a-descriptions-item label="显示字段">
							<template v-if="selectedColumnNames">
								<div class="tag-container">
									<a-tag v-for="name in selectedColumnNames.split('、')" :key="name" color="blue" class="field-tag">{{
										name
									}}</a-tag>
								</div>
							</template>
							<template v-else>未选择</template>
						</a-descriptions-item>
						<a-descriptions-item label="查询条件">
							<template v-if="store.formData.itemConfig?.conditions?.length > 0">
								<div v-for="(condition, index) in store.formData.itemConfig.conditions" :key="index">
									{{ getConditionDescription(condition) }}
								</div>
							</template>
							<template v-else>无</template>
						</a-descriptions-item>
						<a-descriptions-item label="排序配置">
							<template v-if="store.formData.itemConfig?.sorts?.length > 0">
								<div v-for="(sort, index) in store.formData.itemConfig.sorts" :key="index">
									{{ getFieldName(sort.field) }} {{ getSortOrderText(sort.order) }}
								</div>
							</template>
							<template v-else>无</template>
						</a-descriptions-item>
						<a-descriptions-item label="格式化配置">
							<template
								v-if="store.formData.itemConfig.formatConfig && store.formData.itemConfig.formatConfig.length > 0"
							>
								<a-space direction="vertical" style="width: 100%">
									<div
										v-for="(format, index) in store.formData.itemConfig.formatConfig"
										:key="index"
										class="format-card"
									>
										<a-space
											>{{ getFormatDescription(format) }}
											<span class="format-arrow">→</span>
											<a-tag :bordered="false" color="success">{{ getFormatTypeLabel(format.type) }}</a-tag>
											<span class="format-arrow">→</span>
											{{ format.format }}</a-space
										>
									</div>
								</a-space>
							</template>
							<template v-else>无</template>
						</a-descriptions-item>
					</a-descriptions>
				</div>
			</template>
			<a-button type="link" :class="{ 'text-primary bg-primary-1 shadow-sm': visible }" @click="togglePreview">
				<template #icon><eye-outlined /></template>
			</a-button>
		</a-popover>
	</a-tooltip>
</template>

<style scoped>
	.config-preview-panel {
		width: 800px;
		flex-shrink: 0;
		background: white;
		border: 1px solid #e5e7eb;
		border-radius: 2px;
		padding: 16px;
		max-height: calc(100vh - 200px);
		overflow-y: auto;
	}

	.tag-container {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
		max-width: 100%;
		overflow-wrap: break-word;
		word-wrap: break-word;
	}

	.field-tag {
		margin: 0;
		max-width: 100%;
		white-space: normal;
		word-break: break-all;
	}

	.panel-header {
		font-weight: 500;
		margin-bottom: 16px;
	}

	.text-primary {
		color: #1890ff;
	}

	.bg-primary-1 {
		background-color: rgba(24, 144, 255, 0.1);
	}

	.field-tag {
		margin: 0;
	}

	.format-card {
		background-color: #f5f5f5;
		padding: 8px 12px;
		border-radius: 2px;
		margin-bottom: 4px;
		display: flex;
		align-items: center;
	}

	.format-card:last-child {
		margin-bottom: 0;
	}

	.format-arrow {
		color: #1890ff;
		font-weight: bold;
	}
</style>
